<template>
  <div class="question-header">
    <h3>题目 {{ questionIndex + 1 }}</h3>
    <div class="header-actions">
      <el-button v-if="questionIndex === 0" link type="primary" @click="$emit('add-question')">
        <el-icon><Plus /></el-icon>新增题目
      </el-button>
      <el-button link type="danger" @click="$emit('remove-question')"> 删除此题 </el-button>
    </div>
  </div>

  <el-form-item
    :error="errors.title"
    :validate-status="errors.title ? 'error' : ''"
    class="required-label"
    label="题目名称"
    prop="title"
  >
    <el-input
      :model-value="blankForms[questionIndex].title"
      :rows="2"
      placeholder="请输入题目名称"
      type="textarea"
      @update:model-value="(val) => handleUpdateForm('title', val)"
    />
  </el-form-item>

  <el-form-item
    :error="errors.blanks"
    :validate-status="errors.blanks ? 'error' : ''"
    class="required-label"
    label="正确答案"
  >
    <div class="blanks-container">
      <div
        v-for="(blank, index) in blankForms[questionIndex].blanks"
        :key="index"
        class="blank-item"
      >
        <div class="blank-label">填空{{ index + 1 }}</div>
        <el-input
          :model-value="blank"
          :status="errors[`blank${index}`] ? 'error' : ''"
          placeholder="请输入答案"
          @update:model-value="(val) => handleUpdateBlank(questionIndex, index, val)"
        />
        <el-button
          v-if="index > 0"
          circle
          class="delete-btn"
          type="danger"
          @click="removeBlank(questionIndex, index)"
        >
          <el-icon><Delete /></el-icon>
        </el-button>
      </div>
      <div class="add-blank">
        <el-button
          v-if="blankForms[questionIndex].blanks.length < 6"
          link
          type="primary"
          @click="addBlank(questionIndex)"
        >
          <el-icon><Plus /></el-icon>添加填空
        </el-button>
      </div>
    </div>
  </el-form-item>

  <el-form-item label="答案解析" prop="analysis">
    <el-input
      :model-value="blankForms[questionIndex].analysis"
      :rows="3"
      placeholder="请输入答案解析"
      type="textarea"
      @update:model-value="(val) => updateBlankForm(questionIndex, 'analysis', val)"
    />
  </el-form-item>

  <el-form-item
    :error="errors.difficulty"
    :validate-status="errors.difficulty ? 'error' : ''"
    class="required-label"
    label="难度系数"
    prop="difficulty"
  >
    <el-radio-group
      :model-value="blankForms[questionIndex].difficulty"
      @update:model-value="(val) => handleUpdateForm('difficulty', val)"
    >
      <el-radio :value="1">简单</el-radio>
      <el-radio :value="2">中等</el-radio>
      <el-radio :value="3">困难</el-radio>
    </el-radio-group>
  </el-form-item>

  <!-- 添加题目分类选择器 -->
  <el-form-item label="题目分类" prop="classId">
    <class-select
      v-model="blankForms[questionIndex].classId"
      :type="2"
      placeholder="请选择题目分类(选填)"
      @change="(val) => handleUpdateForm('classId', val)"
    />
  </el-form-item>
</template>

<script lang="ts" setup>
import { Delete, Plus } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useQuestionStore } from '@/store/modules/material/question'
import ClassSelect from '../../compont/ClassSelect.vue'

const props = defineProps<{
  questionIndex: number
  tabName?: string
}>()

const questionStore = useQuestionStore()
const { blankForms } = storeToRefs(questionStore)
const { updateBlankForm, addBlank, removeBlank, updateBlank } = questionStore

const errors = ref<Record<string, string>>({})

// 添加实时校验方法
const validateField = (field: string) => {
  const form = blankForms.value[props.questionIndex]
  const questionNumber = props.questionIndex + 1
  const tabPrefix = `【填空题】-第${questionNumber}题：`

  errors.value = { ...errors.value }
  delete errors.value[field]

  switch (field) {
    case 'title':
      if (!form.title?.trim()) {
        errors.value.title = '请输入题目标题'
      }
      break
    case 'blanks':
      const blanks = form.blanks
      const emptyBlankIndex = blanks.findIndex((b) => !b.trim())
      if (emptyBlankIndex !== -1) {
        errors.value[`blank${emptyBlankIndex}`] = '请输入答案'
      }
      break
    case 'difficulty':
      if (!form.difficulty) {
        errors.value.difficulty = '请选择难度系数'
      }
      break
  }
}

// 修改更新表单的方法，添加实时校验
const handleUpdateForm = (field: string, value: any) => {
  updateBlankForm(props.questionIndex, field, value)
  validateField(field)
}

// 修改更新填空答案的方法，添加实时校验
const handleUpdateBlank = (questionIndex: number, blankIndex: number, value: string) => {
  updateBlank(questionIndex, blankIndex, value)
  validateField('blanks')
}

// 校验方法
const validate = () => {
  const errorMessages: string[] = []
  errors.value = {}
  const questionNumber = props.questionIndex + 1
  const tabPrefix = `【填空题】-第${questionNumber}题：`

  if (!blankForms.value[props.questionIndex].title?.trim()) {
    errorMessages.push(`${tabPrefix}请输入题目标题`)
    errors.value.title = '请输入题目标题'
  }

  // 校验填空答案
  const blanks = blankForms.value[props.questionIndex].blanks
  const emptyBlankIndex = blanks.findIndex((b) => !b.trim())
  if (emptyBlankIndex !== -1) {
    errorMessages.push(`${tabPrefix}请输入填空${emptyBlankIndex + 1}的答案`)
    errors.value[`blank${emptyBlankIndex}`] = '请输入答案'
  }

  if (!blankForms.value[props.questionIndex].difficulty) {
    errorMessages.push(`${tabPrefix}请选择难度系数`)
    errors.value.difficulty = '请选择难度系数'
  }

  return {
    valid: errorMessages.length === 0,
    errors: errorMessages
  }
}

const getFormData = () => {
  return {
    ...blankForms.value[props.questionIndex]
  }
}

defineExpose({
  validate,
  getFormData
})

defineEmits(['add-question', 'remove-question'])
</script>

<style lang="scss" scoped>
.blanks-container {
  width: 100%;
}

.blank-item {
  display: flex;
  align-items: center;
  margin-bottom: 16px;

  .blank-label {
    width: 60px;
    text-align: center;
    color: var(--el-text-color-regular);
    background-color: var(--el-fill-color-light);
    padding: 0 8px;
    height: 32px;
    line-height: 32px;
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
    border-right: 1px solid var(--el-border-color);
    font-size: 14px;
  }

  .el-input {
    flex: 1;

    :deep(.el-input__wrapper) {
      border-top-left-radius: 0;
      border-bottom-left-radius: 0;
    }
  }

  .delete-btn {
    flex-shrink: 0;
  }
}

.add-blank {
  margin-top: 8px;
  padding-left: 72px;
}

:deep(.el-form-item) {
  margin-bottom: 22px;

  .el-form-item__label {
    font-weight: 500;
  }
}

:deep(.el-radio-group) {
  .el-radio {
    margin-right: 20px;
    margin-bottom: 8px;
  }
}

.error-message {
  color: var(--el-color-danger);
  font-size: 12px;
  margin-top: 4px;
}

.required-label {
  :deep(.el-form-item__label) {
    &::before {
      content: '*';
      color: var(--el-color-danger);
      margin-right: 4px;
    }
  }
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;

  h3 {
    margin: 0;
    font-size: 16px;
    color: var(--el-text-color-primary);
  }
}
</style>
